package com.vogue.supplymall.account.domain.service.impl;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.vogue.ssm.database.dao.BaseDao;
import com.vogue.ssm.database.util.DealStatus;
import com.vogue.supplymall.account.domain.dao.UserDao;
import com.vogue.supplymall.account.domain.bean.ConstantBean;
import com.vogue.supplymall.account.domain.bean.DataCacheBean;
import com.vogue.supplymall.account.domain.dao.BaseUserInfoDao;
import com.vogue.supplymall.account.domain.dao.CodeDao;
import com.vogue.supplymall.account.domain.dao.RegistinfoDao;
import com.vogue.supplymall.account.domain.dao.RelUserCodeDao;
import com.vogue.supplymall.account.domain.dto.RegistDTO;
import com.vogue.supplymall.account.domain.model.BaseCode;
import com.vogue.supplymall.account.domain.model.BaseRegistinfo;
import com.vogue.supplymall.account.domain.model.BaseUserInfo;
import com.vogue.supplymall.account.domain.model.RelUserCode;
import com.vogue.supplymall.account.domain.model.User;
import com.vogue.supplymall.account.domain.service.UserService;
import com.vogue.supplymall.account.shiro.bean.PasswordBean;
import com.vogue.supplymall.common.constant.ConstantBean.EnumLoginType;
import com.vogue.supplymall.common.domain.dto.OrganInfo;
import com.vogue.supplymall.common.domain.dto.UserInfo;
import com.vogue.supplymall.common.domain.tool.VestUtils;
import com.vogue.supplymall.common.exception.TelRegistRepeatException;
import com.vogue.supplymall.match.domain.service.MatchOrganService;
import com.vogue.supplymall.match.domain.model.MatchOrgan;

/**
 * Created by 崔岳 on 2017-12-1.
 */
@Service("userService")
public class UserServiceImpl extends BaseServiceImpl<User, Long> implements UserService {

	public static final Logger LOGGER_USERSERVICEIMPL = LoggerFactory.getLogger(UserServiceImpl.class);
	
	private UserDao userDao;
	
	@Resource
	private CodeDao codeDao;
	
	@Resource
	private RelUserCodeDao relUserCodeDao;
	
	@Resource
	private RegistinfoDao registinfoDao;
	
	@Resource
	private BaseUserInfoDao baseUserInfoDao;
	
	@Resource
	private MatchOrganService matchOrganService;
	
	public UserServiceImpl(BaseDao<User, Long> baseDao) {
        super(baseDao);
        userDao=(UserDao)baseDao;
	}

	@Override
	public boolean telIsFree(String tel) {
		User user = userDao.selectOneByWhr("tel like '%"
				+ tel + "' or loginname like '%" + tel + "'");
		if(user != null) {
			return false;
		}
		return true;
	}
	
	@Override
	@Transactional
	public String registUser(RegistDTO userdto) {
		String platName = DealStatus.getShade();
		//1.验证是否手机重复注册了
//		BaseRegistinfo info = registinfoDao.selectOneByWhr("registinfo like '%" 
//				+ userdto.getTel() + "' AND registtypeid =" 
//				+ ConstantBean.EnumRegistType.TEL.getCode());

		if(!telIsFree(userdto.getTel())) {
			throw new TelRegistRepeatException(userdto.getTel());
		}
		
		//2.获取一个最新的注册码
		BaseCode syscode = new BaseCode();	
		syscode.setSyscode(DataCacheBean.getInstance().getNewSyscode());
		syscode.setChannel(Integer.parseInt(VestUtils.getTendid()));
		syscode = codeDao.save(syscode);
		
		//3.保存注册用户信息
		PasswordBean pbean = new PasswordBean();
		Map<String, Object> pmap = pbean.newPassword(userdto.getTel(), userdto.getPassword().toCharArray());
		User user = new User();
		user.setLoginname(userdto.getTel());
		user.setTel(userdto.getTel());
		user.setPassword((String)pmap.get(PasswordBean.MAP_KEY_NEWPWD));
		user.setName(userdto.getTel());
		user.setDefsyscodeid(syscode.getId());
		user = userDao.save(user);
		
		//记录用户关联的唯一码
		RelUserCode ruc = new RelUserCode();
		ruc.setSyscodeid(syscode.getId());
		ruc.setUserid(user.getId());
		relUserCodeDao.save(ruc);
		
		//记录用户的注册方式
		BaseRegistinfo rinfo = new BaseRegistinfo();
		rinfo.setSyscodeid(syscode.getId());
		rinfo.setRegistinfo(userdto.getTel());
		if(VestUtils.getOrigin() == null) {
			rinfo.setRegisttypeid((long)ConstantBean.EnumRegistType.TEL.getCode());
		}else {
			switch(VestUtils.getOrigin().toLowerCase()) {
				case "pc" : rinfo.setRegisttypeid((long)ConstantBean.EnumRegistType.PC.getCode());break;
				case "qq" : rinfo.setRegisttypeid((long)ConstantBean.EnumRegistType.QQ.getCode());break;
				case "wechat" : rinfo.setRegisttypeid((long)ConstantBean.EnumRegistType.WECHAT.getCode());break;
				default:
					rinfo.setRegisttypeid((long)ConstantBean.EnumRegistType.TEL.getCode());
			}
		}		
		rinfo.setDisabledflag(true);
		registinfoDao.save(rinfo);
		
		//注册的时候为该账号默认添加一个集团以及下属的门店仓库 -- add 2018-09-11	Begin	
		MatchOrgan organ = saveDefaultOrgan(messageSourceUtils.getMessage("regist.info.defaultEntName", null), 
				messageSourceUtils.getMessage("regist.info.defaultOrganinfo", null),
				0L,
				syscode.getId(),
				1);
		
		organ = saveDefaultOrgan(messageSourceUtils.getMessage("regist.info.defaultOrganName", null), 
				messageSourceUtils.getMessage("regist.info.defaultOrganinfo", null),
				organ.getId(),
				syscode.getId(),
				2);
		
		organ = saveDefaultOrgan(messageSourceUtils.getMessage("regist.info.defaultStoreName", null), 
				messageSourceUtils.getMessage("regist.info.defaultOrganinfo", null),
				organ.getId(),
				syscode.getId(),
				4);
		
		BaseUserInfo baseUserInfo = new BaseUserInfo();
		baseUserInfo.setDisabledflag(false);
		baseUserInfo.setSyscodeid(syscode.getId());
		baseUserInfo.setOrganid(organ.getPid());
		baseUserInfo.setUserid(user.getId());
		baseUserInfoDao.save(baseUserInfo);
		//注册的时候为该账号默认添加一个集团以及下属的门店仓库 -- add 2018-09-11	End	
		
		//无异常的状态下，将新的注册唯一码记录到已生成的系统唯一码内存的存储集合中
		DataCacheBean.getInstance().newSyscodeId(syscode.getSyscode(), syscode.getId());
		return syscode.getSyscode().toString();
	}

	/**
	 * 注册时候生成默认的机构
	 * @param organname 名称
	 * @param organinfo 简介
	 * @param pid	上级id
	 * @param syscodeid	系统编号id
	 * @param type	类型 1：企业 2：门店 3：配送中心 4：仓库
	 * @return
	 */
	@Override
	public MatchOrgan saveDefaultOrgan(String organname, String organinfo, Long pid, Long syscodeid, Integer type) {
		MatchOrgan organ = new MatchOrgan();
		organ.setDisabledflag(false);
		organ.setMcid("0");
		organ.setOrganinfo(organinfo);
		organ.setOrgcode("");
		organ.setOrgname(organname);
		organ.setPid(pid);
		organ.setSign("");
		organ.setSyscodeid(syscodeid);
		if (type == 4) {
		    organ.setMatchid(com.vogue.supplymall.common.constant.ConstantBean.PERSON_STORE_MATCHID);
		} else {
		    organ.setMatchid(com.vogue.supplymall.common.constant.ConstantBean.PERSON_SHOP_MATCHID);  
		}
		organ.setType(type);
		return matchOrganService.save(organ);
	}
	
	@Override
	@Transactional
	public void updatepwd(Long userid, String pwd) {
		// TODO Auto-generated method stub
		User user = userDao.get(userid);
		if(user != null) {
			PasswordBean pbean = new PasswordBean();
			Map<String, Object> pmap = pbean.newPassword(user.getTel(), pwd.toCharArray());
			user.setPassword((String)pmap.get(PasswordBean.MAP_KEY_NEWPWD));
			userDao.update(user);
		}
	}

	@Override
	public OrganInfo defaultOrgan(Long organid) {
		UserInfo userInfo = (UserInfo)SecurityUtils.getSubject().getPrincipal();
//		User user = userDao.get(userInfo.getLoginId());
//		if(user != null) {
//		user.setOrganid(organid);
//		userDao.update(user);
//	}
		BaseUserInfo bu = baseUserInfoDao.selectOneByWhr("userid="+ userInfo.getLoginId());
		if(bu == null) {
			bu = new BaseUserInfo();
			bu.setUserid(userInfo.getLoginId());
			bu.setDisabledflag(false);
			bu.setSyscodeid(userInfo.getSyscodeid());
		}
		bu.setOrganid(organid);
		if(bu.getId() == null || bu.getId().longValue() == 0L) {
			baseUserInfoDao.save(bu);
		}else {
			baseUserInfoDao.update(bu);
		}

		userInfo.setOrganInfo(null);
		userInfo.setLoginUserType(EnumLoginType.PERSON.getCode());
		if(userInfo.getOrganList() != null) {
			for(OrganInfo organ : userInfo.getOrganList()) {
				if(organid.equals(organ.getId())) {
					userInfo.setOrganInfo(organ);
					userInfo.setLoginUserType(EnumLoginType.WORKER.getCode());
					break;
				}
			}
		}		
//		SecurityUtils.getSubject().getSession().touch();
		return userInfo.getOrganInfo();
	}

	@Override
	public User getUserByMatchId(String matchId, Long syscodeId) {
		return userDao.getUserByMatchId(matchId, syscodeId);
	}

	@Override
	public List<User> findUserByMS(String matchIds, Long sysCodeId) {
		return this.selectByWhr(String.format("matchid=%s and defsyscodeid=%d", matchIds, sysCodeId));
	}

	@Override
	public List<User> findUserBySys(Long sysCodeId) {
		return this.selectByWhr(String.format("defsyscodeid=%d", sysCodeId));
	}

	@Override
	public List<User> findUserByTel(String tels) {
		return this.selectByWhr(String.format("tel in (%s)", tels));
	}

	@Override
	public List<User> findUserByTS(String tel, Long sysCodeId) {
		return this.selectByWhr(String.format("tel=%s and defsyscodeid=%d", tel, sysCodeId));
	}

	@Override
	@Transactional
	public void telchange(String tel) {
		// TODO Auto-generated method stub
		if(!telIsFree(tel)) {
			//当前手机号已被其他账户绑定!
			throw new TelRegistRepeatException(tel);
		}else {
			UserInfo userInfo = (UserInfo)SecurityUtils.getSubject().getPrincipal();
			User user = userDao.get(userInfo.getLoginId());
			BaseRegistinfo rInfo = registinfoDao.selectOneByWhr("registinfo='"+user.getTel()+"'");
			if(rInfo != null) {
				rInfo.setRegistinfo(tel);
				registinfoDao.update(rInfo);
			}
			user.setTel(tel);
			user.setLoginname(tel);
			userDao.update(user);
		}
	}

	@Override
	@Transactional
	public void headimgchange(String url) {
		// TODO Auto-generated method stub
		if(url.indexOf("\\") > -1 && url.indexOf("\\\\") < 0) {
			url = url.replaceAll("\\\\", "/");
		}
		
		if(SecurityUtils.getSubject() != null && SecurityUtils.getSubject().getPrincipal() != null) {
			UserInfo userInfo = (UserInfo)SecurityUtils.getSubject().getPrincipal();
			userInfo.setHeadImgUrl(url);
			User user = userDao.get(userInfo.getLoginId());
			user.setHeadimgurl(url);
			userDao.update(user);
		}else {
		    LOGGER_USERSERVICEIMPL.error("缺少必要的登录信息");
		}
	}

	@Override
	public User getUserById(Long userId, Long syscodeId) {
		return userDao.getUserById(userId, syscodeId);
	}
	
}
